package mt.comm;

import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;

class ClientWorker implements Runnable {
	private ConcurrentHashMap<String, Socket> clientMap;
	private Queue<ServerSideMessage> queue;
	private Socket socketFromClient;

	public ClientWorker(ConcurrentHashMap<String, Socket> clientMap,
			final Queue<ServerSideMessage> queue, final Socket socketFromClient) {
		this.clientMap = clientMap;
		this.queue = queue;
		this.socketFromClient = socketFromClient;
	}

	@Override
	public void run() {
		try {
			while (true) {
				ObjectInput ois = new ObjectInputStream(
						socketFromClient.getInputStream());
				ServerSideMessage message = (ServerSideMessage) ois
						.readObject();
				
				switch (message.getType()) {
					case CONNECTED:
						clientMap.put(message.getSenderNickname(), socketFromClient);
						break;
					case DISCONNECTED:
						clientMap.remove(message.getSenderNickname());
						break;
					default:
						// do nothing
						break;
				}
				
				queue.add(message);
			}
		} catch (Throwable t) {
			return;
		}
	}
}